package com.cwvs.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cwvs.helper.FileUploadHelper;
import com.cwvs.models.AppFunction;
import com.cwvs.services.AppFunctionService;
import com.cwvs.services.AppUserService;
import com.cwvs.utils.AppUtil;
import com.cwvs.utils.CommonUtils;
import com.cwvs.utils.Constant;
import com.cwvs.utils.JsonUtil;
import com.google.code.kaptcha.Constants;

@Controller
public class AdminController {

	@Resource
	private AppFunctionService appFunctionService;
	@Resource
	private AppUserService appUserService;
	@Resource
	private FileUploadHelper fileUploadHelper;
	@RequestMapping("/")
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		String admin_name = (String) request.getSession().getAttribute(
				Constant.ADMIN_NAME);
		Object obj = request.getSession()
				.getAttribute(Constant.ADMIN_REAL_NAME);
		if (null != obj) {
			String admin_real_name = obj.toString();
			mav.addObject("admin_real_name", "-" + admin_real_name);
		}
		mav.setViewName("/admin_index");
		if (StringUtils.isBlank(admin_name)) {
			mav.setViewName("/html/login");
			return mav;
		}
		mav.addObject("tree", function_accordion_jsondata(request));
		mav.addObject("admin_name", admin_name);
		mav.addObject("now_date", AppUtil.formatDate(new Date()));

		return mav;
	}

	/**
	 * 主菜单树
	 */
	public String function_accordion_jsondata(HttpServletRequest request) {
		List<Object> ret = new ArrayList<Object>();
		List<AppFunction> allowFunctionList = allowFunctions((String) request
				.getSession().getAttribute(Constant.ADMIN_ID), (String) request
				.getSession().getAttribute(Constant.ADMIN_NAME));
		AppFunction root = appFunctionService.getRoot();
		if (null == root)
			return null;

		List<AppFunction> list = appFunctionService
				.findAppFunctionsByParent(root.getId());
		if (null == list || list.size() < 1)
			return null;

		for (int i = 0; i < list.size(); i++) {
			AppFunction appFunction = list.get(i);
			if (!appFunction.isFunctionMenu() && !appFunction.isMenu()) {
				continue;
			}
			if (contains(allowFunctionList, appFunction)) {
				HashMap<String, Object> hashMap = to_menu_tree_node(
						root.getId(), appFunction, allowFunctionList, request);
				String jsonData = JsonUtil.toJson(hashMap);
				HashMap<String, Object> this_node = new HashMap<String, Object>();
				this_node.put("xtype", "treepanel");
				this_node.put("title", appFunction.getName());
				this_node.put("autoScroll", true);
				this_node.put("containerScroll", true);
				this_node.put("animate", true);
				this_node.put("border", false);
				this_node.put("rootVisible", false);
				this_node.put("loader", "new Ext.tree.TreeLoader()");
				this_node.put("root", "new Ext.tree.AsyncTreeNode(" + jsonData
						+ ")");
				ret.add(this_node);
			}
		}
		String result = JsonUtil.toJson(ret).replace("\\\"", "\"");
		result = result.replace("\"new", "new");
		result = result.replace("\"(", "(");
		result = result.replace("\"{", "{");
		result = result.replace(")\"", ")");
		result = result.replace("}\"", "}");
		result = result.replace("\"function", "function");
		result = result.replace("\"execute_remote_extjs",
				"execute_remote_extjs");
		return result;
	}

	public List<AppFunction> allowFunctions(String id, String userName) {
		List<String> list = appFunctionService.allowFunctions(id, userName);
		List<AppFunction> appFunctionList = new ArrayList<AppFunction>();
		for (String appFunctionId : list) {
			if (StringUtils.isNotBlank(appFunctionId)) {
				AppFunction af = new AppFunction();
				af.setId(appFunctionId);
				appFunctionList.add(af);
			}
		}

		return appFunctionList;
	}

	/**
	 * 主菜单树的一个节点
	 * 
	 * @param appfunction
	 * @param allowFunctionList
	 * @return
	 */
	private HashMap<String, Object> to_menu_tree_node(String rootId,
			AppFunction appfunction, List<AppFunction> allowFunctionList,
			HttpServletRequest request) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		List<Object> extChildrenNode = new ArrayList<Object>();
		List<AppFunction> menuChildren = appFunctionService
				.findAppFunctionsByParent(appfunction.getId());

		boolean leaf = false;
		if (null == menuChildren || menuChildren.size() < 1) {
			leaf = true;
		}
		map.put("text", appfunction.getName());
		map.put("leaf", appfunction.isFunctionMenu());
		map.put("hidden", !contains(allowFunctionList, appfunction));
		if (!appfunction.isFunctionMenu() && !appfunction.isMenu()) {
			map.put("hidden", true);
		}
		map.put("singleClickExpand", !leaf);
		if (appfunction.getParentId() != rootId) {
			map.put("expanded", true);
		}

		for (int i = 0; i < menuChildren.size(); i++) {
			extChildrenNode.add(to_menu_tree_node(rootId, menuChildren.get(i),
					allowFunctionList, request));
		}
		map.put("children", extChildrenNode);

		if (StringUtils.isNotBlank(appfunction.getHandlerMethod())
				&& StringUtils.isNotBlank(appfunction.getHandlerUrl())) {
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("click", appfunction.getHandlerMethod()
					+ ".createCallback" + "('" + request.getRequestURI()
					+ appfunction.getHandlerUrl() + "')");
			map.put("listeners", hashMap);
		} else if (StringUtils.isNotBlank(appfunction.getHandler())) {
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("click", "function(n){" + appfunction.getHandler()
					+ "}");
			map.put("listeners", hashMap);
		} else {
			if (appfunction.isFunctionMenu()) {
				map.put("disabled", true);
			}
		}
		return map;
	}

	private boolean contains(List<AppFunction> list, AppFunction appFunction) {
		for (AppFunction af : list) {
			if (StringUtils.equals(af.getId(), appFunction.getId())) {
				return true;
			}
		}
		return false;
	}

	@RequestMapping("/user/login")
	public ModelAndView login(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		ModelAndView mv = new ModelAndView("html/login");
		mv.addObject("title", "用户登录");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String validateCode = request.getParameter("j_captcha_response");

		if (StringUtils.isBlank(username)) {
			mv.addObject("error_message", "请输入用户名");
			return mv;
		}
		if (StringUtils.isBlank(password)) {
			mv.addObject("error_message", "请输入密码");
			return mv;
		}
		if (StringUtils.isBlank(validateCode)) {
			mv.addObject("error_message", "请输入验证码");
			return mv;
		}
		String captcha_word = "".concat((String) request.getSession()
				.getAttribute(Constants.KAPTCHA_SESSION_KEY));
		if (!StringUtils.equalsIgnoreCase(captcha_word, validateCode)) {
			mv.addObject("error_message", "验证码错误");
			return mv;
		}
		Map<String, Object> m = appUserService.getAdminUserByMobile(username);
		if (null == m) {
			mv.addObject("error_message", "用户名或密码错误");
			return mv;
		}
		String passwordSalt = MapUtils.getString(m, "PASSWORD_SALT");
		if (StringUtils.isNotEmpty(passwordSalt)) {
			password = password.concat(passwordSalt);
		}
		String psdMd5 = CommonUtils.executeMD5(password);
		String pwd = MapUtils.getString(m, "PASSWORD");
		if (!psdMd5.equals(pwd)) {
			mv.addObject("error_message", "用户名或密码错误");
			return mv;
		}
		HttpSession session = request.getSession();
		session.setAttribute(Constant.ADMIN_ID, MapUtils.getString(m, "ID"));
		session.setAttribute(Constant.ADMIN_NAME,
				MapUtils.getString(m, "USERNAME"));
		session.setAttribute(Constant.ADMIN_REAL_NAME,
				MapUtils.getString(m, "USERNAME"));
		return new ModelAndView("redirect:/");
	}

	/**
	 * 退出
	 * 
	 * @return
	 */
	@RequestMapping("/user/logout")
	public ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("html/login");
		HttpSession session = request.getSession();
		session.removeAttribute(Constant.ADMIN_ID);
		session.removeAttribute(Constant.ADMIN_NAME);
		session.removeAttribute(Constant.ADMIN_REAL_NAME);
		mv.addObject("title", "用户登录");
		return mv;
	}
    @RequestMapping("/login/extjs")
    @ResponseBody
    public Map<String,Object>  loginExtjs(){
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("success", "false");
        map.put("errormsg", "您的闲置时间过长，请重新刷新浏览器");
        return map;
    }
}
